import pymysql
import re

class Dict:
    def __init__(self):
        self.kwargs = {
            "host": "localhost",
            "port": 3306,
            "user": "root",
            "password": "root",
            "database": "dict",
            "charset": "utf8"
        }

        # 数据库连接
        self.db = pymysql.connect(**self.kwargs)

        # 创建游标
        self.cur = self.db.cursor()

    def get_data(self):
        data = []
        # 打开文件
        file = open('dict.txt')
        # 读取文件
        # 方法1 字符串处理
        # for f in file:
        #     word,mean = f.split(' ',1)
        #     data.append((word,mean.strip()))

        # 方法2 正则处理
        for line in file:
            # [(word,mean))
            data += re.findall("(\w+)\s+(.+)", line)
        file.close()
        return data

    def insert_word(self):
        data = self.get_data()
        try:
            # sql = "create table dict(id int primary key auto_increment,word varchar(50),menu varchar(1024))"
            # cur.execute(sql)
            sql = "insert into dict (word,menu) values(%s,%s)"
            self.cur.executemany(sql, data)
        except Exception as e:
            print(e)
            self.db.rollback()
        else:
            self.db.commit()

    def close(self):
        # 关闭
        self.cur.close()
        self.db.close()

# kwargs = {
#     "host": "localhost",
#     "port": 3306,
#     "user": "root",
#     "password": "root",
#     "database": "dict",
#     "charset": "utf8"
# }
#
# # 数据库连接
# db = pymysql.connect(**kwargs)
#
# # 创建游标
# cur = db.cursor()



if __name__ == '__main__':
    dict = Dict() #实例化
    dict.insert_word() #调用方法
    dict.close()